package main

import (
	"encoding/json"
	"fmt"
	"strconv"
	"strings"
	"time"

	"gitee.com/fcsvr/fc/fclog"
	"github.com/tidwall/gjson"
)

func SetAlphaHidden(alphaid string) {
	//alphaid = "Gb0lWzZ"
	type Param struct {
		Hidden bool `josn:"hidden"`
	}
	param := Param{
		Hidden: true,
	}

	url := "https://api.worldquantbrain.com/alphas/" + alphaid
	paramJson, _ := json.Marshal(param)
	resp, _ := G_Client.R().SetHeader("Content-Type", "application/json").SetBody(paramJson).Patch(url)
	//fmt.Printf("code:%v, body: %v\n", resp.StatusCode(), string(resp.Body()))
	fclog.Info("SetAlphaHidden AlphaID = %v, code = %v", alphaid, resp.StatusCode())
}

func SetAlphaColor(alphaid string, color string) {
	//alphaid = "Gb0lWzZ"
	type Param struct {
		Color string `josn:"color"`
	}
	param := Param{
		Color: color,
	}

	url := "https://api.worldquantbrain.com/alphas/" + alphaid
	paramJson, _ := json.Marshal(param)
	resp, _ := G_Client.R().SetHeader("Content-Type", "application/json").SetBody(paramJson).Patch(url)
	//fmt.Printf("code:%v, body: %v\n", resp.StatusCode(), string(resp.Body()))
	fclog.Info("SetAlphaColor AlphaID = %v, code = %v, color = %s", alphaid, resp.StatusCode(), color)
}

func SetHiddenAlphas(region string) {
	now := time.Now()
	year, month, day := now.Year(), now.Month(), now.Day()
	startDate := fmt.Sprintf("%d-%d-%d", year, month, day)

	offset := 0
	baseurl := "https://api.worldquantbrain.com/users/self/alphas?limit=100&offset=%d&status=UNSUBMITTED%%1FIS_FAIL&dateCreated%%3C=%sT00:00:00-04:00&settings.region=%s&order=-is.sharpe&hidden=false&type!=SUPER"
	url := fmt.Sprintf(baseurl, offset, startDate, region)
	fclog.Info(url)

	resp, _ := G_Client.R().SetHeader("Content-Type", "application/json").Get(url)
	strBody := string(resp.Body())
	count := gjson.Get(strBody, "count").Int()
	fclog.Info("Alpha count = %d", count)
	for i := 0; i < int(count); i += 100 {
		url = fmt.Sprintf(baseurl, i, startDate, region)
		resp, _ := G_Client.R().SetHeader("Content-Type", "application/json").Get(url)
		strBody := string(resp.Body())
		for j := 0; j < 100; j++ {
			index := "results." + strconv.Itoa(j)
			if !gjson.Get(strBody, index).Exists() {
				break
			}
			index_code := index + ".regular.code"
			index_id := index + ".id"
			alpha := gjson.Get(strBody, index_code).String()
			alpha = strings.ReplaceAll(alpha, "\r\n", "")
			id := gjson.Get(strBody, index_id).String()
			SetAlphaHidden(id)
			fclog.Info("%d", i)
		}
	}
}

func SetHiddenAlphasBySameExpress(express string, region string) {
	now := time.Now()
	year, month, day := now.Year(), now.Month(), now.Day()
	day0 := day - 2
	if day0 < 1 {
		day0 = 1
	}
	startDate := fmt.Sprintf("%d-%d-%d", year, month, day0)

	offset := 0
	baseurl := "https://api.worldquantbrain.com/users/self/alphas?limit=100&offset=%d&status=UNSUBMITTED%%1FIS_FAIL&dateCreated%%3E=%sT00:00:00-04:00&settings.region=%s&order=-is.sharpe&hidden=false&type!=SUPER"
	url := fmt.Sprintf(baseurl, offset, startDate, region)
	fclog.Info(url)

	resp, _ := G_Client.R().SetHeader("Content-Type", "application/json").Get(url)
	strBody := string(resp.Body())
	count := gjson.Get(strBody, "count").Int()
	fclog.Info("Alpha positive count = %d", count)
	for i := 0; i < int(count); i += 100 {
		url = fmt.Sprintf(baseurl, i, startDate, region)
		resp, _ := G_Client.R().SetHeader("Content-Type", "application/json").Get(url)
		strBody := string(resp.Body())
		for j := 0; j < 100; j++ {
			index := "results." + strconv.Itoa(j)
			if !gjson.Get(strBody, index).Exists() {
				break
			}
			index_code := index + ".regular.code"
			index_id := index + ".id"
			alpha := gjson.Get(strBody, index_code).String()
			alpha = strings.ReplaceAll(alpha, "\r\n", "")
			if strings.TrimSpace(alpha) == strings.TrimSpace(express) {
				fclog.Info("%s", alpha)
				id := gjson.Get(strBody, index_id).String()
				SetAlphaHidden(id)
				fclog.Info("%d", i)
			}
		}
	}
}

func SetHiddenAlphasByActive(startdate string, enddate string, fitness float32, region string) {
	activeAlphas := GetActiveAlphas("USA")

	offset := 0
	baseurl := "https://api.worldquantbrain.com/users/self/alphas?limit=100&offset=%d&status=UNSUBMITTED%%1FIS_FAIL&dateCreated%%3E=2025-%sT00:00:00-04:00&dateCreated%%3C2025-%sT00:00:00-04:00&is.fitness%%3E%f&settings.region=%s&order=-is.sharpe&hidden=false&type!=SUPER"
	url := fmt.Sprintf(baseurl, offset, startdate, enddate, fitness, region)
	fclog.Info(url)

	resp, _ := G_Client.R().SetHeader("Content-Type", "application/json").Get(url)
	strBody := string(resp.Body())
	count := gjson.Get(strBody, "count").Int()
	fclog.Info("Alpha positive count = %d", count)
	for i := 0; i < int(count); i += 100 {
		url = fmt.Sprintf(baseurl, i, startdate, enddate, fitness, region)
		resp, _ := G_Client.R().SetHeader("Content-Type", "application/json").Get(url)
		strBody := string(resp.Body())
		for j := 0; j < 100; j++ {
			index := "results." + strconv.Itoa(j)
			if !gjson.Get(strBody, index).Exists() {
				break
			}
			index_code := index + ".regular.code"
			index_id := index + ".id"
			alpha := gjson.Get(strBody, index_code).String()
			alpha = strings.ReplaceAll(alpha, "\r\n", "")
			if _, ok := activeAlphas[alpha]; ok {
				fclog.Info("%s", alpha)
				id := gjson.Get(strBody, index_id).String()
				SetAlphaHidden(id)
				fclog.Info("%d", i)
			}
		}
	}
}

func SetHiddenAlphasByFitness(startdate string, enddate string, region string) {
	offset := 0
	baseurl := "https://api.worldquantbrain.com/users/self/alphas?limit=100&offset=%d&status=UNSUBMITTED%%1FIS_FAIL&dateCreated%%3E=%sT00:00:00-04:00&dateCreated%%3C%sT00:00:00-04:00&is.fitness%%3C0.8&is.fitness%%3E-0.8&is.sharpe%%3C1.4&is.sharpe%%3E-1.4&settings.region=%s&order=-is.sharpe&hidden=false&type!=SUPER"
	url := fmt.Sprintf(baseurl, offset, startdate, enddate, region)
	fmt.Println(url)

	resp, _ := G_Client.R().SetHeader("Content-Type", "application/json").Get(url)
	strBody := string(resp.Body())
	count := gjson.Get(strBody, "count").Int()
	fclog.Info("SetHiddenAlphasByFitness Alpha hidden count = %d", count)
	for i := 0; i < int(count); i += 100 {
		url = fmt.Sprintf(baseurl, i, startdate, enddate, region)
		resp, _ := G_Client.R().SetHeader("Content-Type", "application/json").Get(url)
		strBody := string(resp.Body())
		for j := 0; j < 100; j++ {
			index := "results." + strconv.Itoa(j)
			if !gjson.Get(strBody, index).Exists() {
				break
			}
			index_code := index + ".regular.code"
			index_id := index + ".id"
			alpha := "-" + gjson.Get(strBody, index_code).String()
			alpha = strings.ReplaceAll(alpha, "\r\n", "")
			id := gjson.Get(strBody, index_id).String()
			SetAlphaHidden(id)
			//fmt.Printf("%s\n", alpha)
			fclog.Debug("SetAlphaHidden id = %v, count j = %v", id, j)
		}
		fclog.Debug("count i = %v", i)
	}
}

func SetHiddenAlphasByCount(startdate string, enddate string, region string) {
	offset := 0
	baseurl := "https://api.worldquantbrain.com/users/self/alphas?limit=100&offset=%d&status=UNSUBMITTED%%1FIS_FAIL&dateCreated%%3E=%sT00:00:00-04:00&dateCreated%%3C%sT00:00:00-04:00&is.longCount%%3C1&is.shortCount%%3C1&settings.region=%s&order=-is.sharpe&hidden=false&type!=SUPER"
	url := fmt.Sprintf(baseurl, offset, startdate, enddate, region)
	//fmt.Println(url)

	resp, _ := G_Client.R().SetHeader("Content-Type", "application/json").Get(url)
	strBody := string(resp.Body())
	count := gjson.Get(strBody, "count").Int()
	fclog.Info("SetHiddenAlphasByCount Alpha hidden count = %d", count)
	for i := 0; i < int(count); i += 100 {
		url = fmt.Sprintf(baseurl, i, startdate, enddate, region)
		resp, _ := G_Client.R().SetHeader("Content-Type", "application/json").Get(url)
		strBody := string(resp.Body())
		for j := 0; j < 100; j++ {
			index := "results." + strconv.Itoa(j)
			if !gjson.Get(strBody, index).Exists() {
				break
			}
			index_code := index + ".regular.code"
			index_id := index + ".id"
			alpha := "-" + gjson.Get(strBody, index_code).String()
			alpha = strings.ReplaceAll(alpha, "\r\n", "")
			id := gjson.Get(strBody, index_id).String()
			SetAlphaHidden(id)
			//fmt.Printf("%s\n", alpha)
			fclog.Debug("SetAlphaHidden id = %v, count j = %v", id, j)
		}
		fclog.Info("%d", i)
	}
}

func SubmitAlpha() {
	alphaid := ""
	url := "https://api.worldquantbrain.com/alphas/" + alphaid + "/submit"
	resp, err := G_Client.R().SetHeader("Content-Type", "application/json").Post(url)
	fclog.Debug("SubmitAlpha header body: %v, %v", err, string(resp.Body()))
	_, exists := resp.Header()["Location"]
	if exists {
		for {
			resp, _ = G_Client.R().SetHeader("Content-Type", "application/json").Get(url)
			fclog.Debug("SubmitAlpha %s now, %v", alphaid, resp)
			if _, exists := resp.Header()["Retry-After"]; !exists {
				break
			}
			time.Sleep(time.Second * 120)
		}
	}
	fclog.Debug("SubmitAlpha %d success", alphaid)
}
